#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080
#define MAX_BUFFER_SIZE 1024

int main() {
    int sockfd;
    struct sockaddr_in servaddr;
    char buffer[MAX_BUFFER_SIZE];
    const char *message = "Hello from Client";

    // 创建UDP套接字
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    memset(&servaddr, 0, sizeof(servaddr));

    // 为服务器地址填充结构
    servaddr.sin_family = AF_INET; // IPv4
    servaddr.sin_port = htons(PORT); // 端口
    // 假设服务器IP地址为本地环回地址
    if (inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr) <= 0) {
        perror("Invalid address");
        exit(EXIT_FAILURE);
    }

    // 发送消息到服务器
    sendto(sockfd, message, strlen(message), 0, (const struct sockaddr *)&servaddr, sizeof(servaddr));
    printf("Message sent.\n");

    // 接收服务器响应
    socklen_t len = sizeof(servaddr);
    int n = recvfrom(sockfd, (char *)buffer, MAX_BUFFER_SIZE, 0, (struct sockaddr *)&servaddr, &len);
    if (n < 0) {
        perror("recvfrom failed");
    } else {
        printf("Server response: %s\n", buffer);
    }

    close(sockfd);
    return 0;
}